import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

/* Layout */
import Layout from '@/layout'

/**
 * Note: sub-menu only appear when route children.length >= 1
 * Detail see: https://panjiachen.github.io/vue-element-admin-site/guide/essentials/router-and-nav.html
 *
 * hidden: true                   if set true, item will not show in the sidebar(default is false)
 * alwaysShow: true               if set true, will always show the root menu
 *                                if not set alwaysShow, when item has more than one children route,
 *                                it will becomes nested mode, otherwise not show the root menu
 * redirect: noRedirect           if set noRedirect will no redirect in the breadcrumb
 * name:'router-name'             the name is used by <keep-alive> (must set!!!)
 * meta : {
    roles: ['admin','editor']    control the page roles (you can set multiple roles)
    title: 'title'               the name show in sidebar and breadcrumb (recommend set)
    icon: 'svg-name'/'el-icon-x' the icon show in the sidebar
    breadcrumb: false            if set false, the item will hidden in breadcrumb(default is true)
    activeMenu: '/example/list'  if set path, the sidebar will highlight the path you set
  }
 */

/**
 * routes
 * a base page that does not have permission requirements
 * all roles can be accessed
 */
var routes = [{
    path: '/login',
    component: () => import('@/views/login/index'),
    hidden: true
  },

  {
    path: '/404',
    component: () => import('@/views/404'),
    hidden: true
  },
  {//必需在最后
    path: '*',
    redirect: '/404',
    hidden: true
  }
]


/**
 * asyncRoutes
 * the routes that need to be dynamically loaded based on user roles
 */
var asyncPath = [{
    path: '/',
    name: 'dashboard',
    component: Layout,
    redirect: '/dashboard',
    hidden: false,
    children: [{
      path: 'dashboard',
      name: 'dashboardIndex',
      component: () => import('@/views/dashboard/index'),
      hidden: false,
      meta: {
        title: '仪表盘',
        icon: 'dashboard'
      }
    }]
  },
  {
    path: '/attachment',
    name: 'attachment',
    component: Layout,
    redirect: '/attachment/index',
    hidden: false,
    children: [{
      path: 'attachment',
      name: 'attachmentIndex',
      component: () => import('@/views/attachment/index'),
      hidden: false,
      meta: {
        title: '附件管理',
        icon: 'el-icon-folder'
      }
    }]
  },

  {
    path: '/system',
    name: 'system',
    component: Layout,
    redirect: '/system/setting/site_setting',
    meta: {
      title: '系统',
      icon: 'el-icon-setting'
    },
    hidden: false,
    children: [{
        path: 'setting',
        name: 'systemSetting',
        component: () => import('@/views/system/setting/index'),
        redirect: '/setting/site_setting',
        meta: {
          title: '设置',
          icon: 'el-icon-edit-outline'
        },
        hidden: false,
        children: [{
            path: 'site_setting',
            name: 'systemSiteSetting',
            component: () => import('@/views/system/setting/site_setting'),
            hidden: false,
            meta: {
              title: '站点设置',
              icon: ''
            }
          },
          {
            path: 'user_setting',
            name: 'systemUserSetting',
            component: () => import('@/views/system/setting/user_setting'),
            hidden: false,
            meta: {
              title: '用户设置',
              icon: ''
            }
          }
        ]
      },

      {
        path: '/site',
        name: 'systemSite',
        component: () => import('@/views/site/index'),
        redirect: '/site/carousel',
        meta: {
          title: '站点',
          icon: 'site'
        },
        hidden: false,
        children: [{
            path: 'carousel',
            name: 'systemSiteCarousel',
            component: () => import('@/views/site/carousel'),
            meta: {
              title: '轮播图',
              icon: 'el-icon-s-help'
            },
            hidden: false,
          },
          {
            path: 'sms',
            name: 'systemSiteSms',
            component: () => import('@/views/site/sms'),
            meta: {
              title: '验证码',
              icon: 'el-icon-s-comment'
            },
            hidden: false,
          }
        ],
      },
    ]
  },

  {
    path: '/rbac',
    component: Layout,
    redirect: 'role',
    name: 'rbac',
    meta: {
      title: '权限管理',
      icon: 'el-icon-setting'
    },
    hidden: false,
    children: [{
        path: 'role',
        name: 'rbacRole',
        component: () => import('@/views/rbac/role'),
        meta: {
          title: '角色',
          icon: 'el-icon-user'
        },
        hidden: false,
      },
      {
        path: 'role_user',
        name: 'rbacRoleUser',
        component: () => import('@/views/rbac/role_user'),
        meta: {
          title: '角色用户',
          icon: 'el-icon-user'
        },
        hidden: true
      },
      {
        path: 'permission',
        name: 'rbacPermission',
        component: () => import('@/views/rbac/permission'),
        meta: {
          title: '权限',
          icon: 'el-icon-setting'
        },
        hidden: false,
      },
      {
        path: 'rule',
        name: 'rbacRule',
        component: () => import('@/views/rbac/rule'),
        meta: {
          title: '规则',
          icon: 'el-icon-setting'
        },
        hidden: false,
      },
      {
        path: 'menu',
        name: 'rbacMenu',
        component: () => import('@/views/rbac/menu'),
        meta: {
          title: '菜单',
          icon: 'el-icon-s-order'
        },
        hidden: false,
      }
    ],
  },
  {
    path: '/user',
    component: Layout,
    redirect: '/user/list/index',
    name: 'user',
    meta: {
      title: '用户管理',
      icon: 'el-icon-user'
    },
    hidden: false,
    children: [{
        path: 'list/index',
        name: 'userList',
        component: () => import('@/views/user/list/index'),
        hidden: false,
        meta: {
          title: '用户列表',
          icon: ''
        }
      },
      {
        path: 'profile/index',
        name: 'userProfile',
        component: () => import('@/views/user/profile/index'),
        meta: {
          title: '用户详情',
          icon: ''
        },
        hidden: true
      }
    ]
  }
];
// 检查菜单是否授权
function checkMenu(data) {
  // 整理菜单
  var menus = JSON.parse(localStorage.getItem('menus_token'))
  var has = false;
  for (let i in data) {
    if (menus.findIndex(v => v == data[i].name) == -1) { //未找到菜单 检查 找到的不用管
      if (!data[i].children) {
        // 菜单未授权且没有下级菜单 隐藏
        data[i].hidden = true
        continue
      } else {
        if (data[i].children.length > 0) {
          // 有下级菜单，检查下级 递归
          if (checkMenu(data[i].children) === false) {
            //下级菜单也没有授权 隐藏
            data[i].hidden = true
          }
        }
      }
    } else { //只需要找到一次
      has = true
    }
  }
  return has;
}

function getRoutes() {
  try {
    var menus = JSON.parse(localStorage.getItem('menus_token'))
    // 整理菜单
    for (let i in asyncPath) {
      if (menus.findIndex(v => v == asyncPath[i].name) == -1) { //未找到菜单 检查 找到的不用管
        if (!asyncPath[i].children) {
          // 菜单未授权且没有下级菜单 隐藏
          asyncPath[i].hidden = true
          continue
        } else if (asyncPath[i].children.length > 0) {
          // 有下级菜单，检查下级
          if (checkMenu(asyncPath[i].children) === false) {
            //下级菜单也没有授权 隐藏
            asyncPath[i].hidden = true
          }
        } else {
          asyncPath[i].hidden = true
        }
      }
    }
  } catch (e) {
    console.log(e, 'menus is error')
  }
  let i = asyncPath.findIndex(v => v.path == '/')
  if (i == -1) {
    asyncPath.push({
      path: '/',
      name: 'dashboard',
      component: Layout,
      redirect: '/dashboard',
      children: [{
        path: 'dashboard',
        name: 'dashboardIndex',
        component: () => import('@/views/dashboard/index'),
        meta: {
          title: '仪表盘',
          icon: 'dashboard'
        }
      }]
    })
  }
  return asyncPath.concat(routes);
}

export const constantRoutes = getRoutes()

const createRouter = () => new Router({
  // mode: 'history', // require service support
  scrollBehavior: () => ({
    y: 0
  }),
  routes: getRoutes()
})

const router = createRouter()

// Detail see: https://github.com/vuejs/vue-router/issues/1234#issuecomment-357941465
export function resetRouter() {
  console.log('resetRouter')
  const newRouter = createRouter()
  router.matcher = newRouter.matcher // reset router
}

export default router
